package manage.handler;


import manage.service.StudentService;
import manage.service.impl.StudentServiceImpl;
import manage.student.MainView;
import manage.student.view.AddStudentView;
import manage.student.view.UpdateStudentView;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class MainViewHandler implements ActionListener{
    private MainView mainView;
    public MainViewHandler(MainView mainView){
        this.mainView=mainView;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        JButton jButton=(JButton) e.getSource();
        String Text=jButton.getText();
        if(Text.equals("添加")){
            new AddStudentView(mainView);
        } else if (Text.equals("删除")) {
            int[]selectedStudentIds= mainView.getSelectedStudentIds();
            if(selectedStudentIds.length==0){
                JOptionPane.showMessageDialog(mainView,"请选择要删除的行");
                return;
            }
            int option =JOptionPane.showConfirmDialog(mainView,"确认要删除选择的"+selectedStudentIds.length+"行吗?",
                    "确认删除",JOptionPane.YES_NO_OPTION);
            if(option==JOptionPane.YES_OPTION){//确认删除
                StudentService studentService=new StudentServiceImpl();
                boolean deleteResult=studentService.delete(selectedStudentIds);
                if(deleteResult){
                    //更新表格数据
                    mainView.reloadTable();
                    JOptionPane.showMessageDialog(mainView,"删除成功");
                }else{
                    JOptionPane.showMessageDialog(mainView,"删除失败");
                }
            }

        } else if (Text.equals("修改")) {
            int[]selectedStudentIds= mainView.getSelectedStudentIds();
            if(selectedStudentIds.length!=1){
                JOptionPane.showMessageDialog(mainView,"一次只能修改一行");
                return;
            }
            new UpdateStudentView(mainView,selectedStudentIds[0]);
        } else if (Text.equals("搜索")) {
            mainView.setPageNow(1);
            mainView.reloadTable();
        } else if (Text.equals("上一页")) {
            mainView.setPageNow(mainView.getPageNow()-1);
            System.out.println(mainView.getPageNow());
            mainView.reloadTable();
        } else if (Text.equals("下一页")) {
            mainView.setPageNow(mainView.getPageNow()+1);
            System.out.println(mainView.getPageNow());
            mainView.reloadTable();
        }
    }
}
